<?php
/**
 * Created by PhpStorm.
 * User: liuzh
 * Date: 2016/1/18
 * Time: 14:31
 */

header("Content-Type:application/json;charset=utf-8");
//    $filename=scandir("./Upload/");
//    for ($i=0; $i<count($filename); $i++){
//        if(is_dir($filename[$i]))
//            continue;
//        else{
//            $FILES[] = $filename[$i];
//        }
//    }
//    print_r($FILES);

//phpinfo();

require_once ("conf.php");
$link = CONNECT();

if(isset($_POST["deleteFolder"])){
    $folder = $_POST["deleteFolder"];

    if($folder == "delete"){
        echo json_encode("Please select a folder");
        return;
    }

    $sql = "delete from pictures where folder='$folder'";
//    echo $sql;
    $result = mysqli_query($link,$sql);

    $DIR = $PICTURES.$folder;

    if (DIRECTORY_SEPARATOR == "\\") { //windows os
        $DIR = iconv('utf-8', 'gbk', $DIR);
    }

    $dh=opendir($DIR);
    while ($file=readdir($dh)) {
        if($file!="." && $file!="..") {
            $fullpath=$DIR."/".$file;
            if(!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath);
            }
        }
    }

    closedir($dh);
    //删除当前文件夹：
    if(rmdir($DIR)) {
        echo json_encode("Delect Success!");
        return true;
    } else {
        echo json_encode("Delect folder failed!");
        return false;
    }
}

if(isset($_POST["deletePicID"])){
    $sql = "select folder,name from pictures where p_id=".$_POST["deletePicID"];
    $result = mysqli_query($link,$sql);
    $row = mysqli_fetch_row($result);

    $DIR = $PICTURES.$row[0];
    if (DIRECTORY_SEPARATOR == "\\") { //windows os
        $DIR = iconv('utf-8', 'gbk', $DIR);
    }
    $fullpath=$DIR."/".$row[1];
    if(unlink($fullpath)){
        $sql = "delete from pictures where p_id=".$_POST["deletePicID"];
        $result = mysqli_query($link,$sql);

        if($result) {
            echo json_encode("delete success!");
        }else
            echo json_encode("delete fail!");
    }else
        echo json_encode("delete fail!");

    return;
}

if($_GET['TYPE'] == "image"){
    $folder = $_GET['folder'];
    $sql = "select * from pictures LEFT JOIN description on pictures.desc_id=description.d_id where pictures.folder='$folder' order by pictures.p_id";
    $result = mysqli_query($link,$sql);
    while($row = mysqli_fetch_assoc($result)){
        $IMAGE[] = array($row["name"],$row["height"],$row["width"],$row["date"],$row["title"],$row["description"],$row["p_id"]);
    }
    if(!isset($IMAGE)) {
        echo json_encode("No Image");
    }else
        echo json_encode($IMAGE);
}elseif($_GET['TYPE'] == "folder") {
    $sql = "SELECT DISTINCT folder from pictures ORDER BY folder";
    $result = mysqli_query($link,$sql);
    while($row = mysqli_fetch_assoc($result)){
        $FOLDER[] = $row['folder'];
    }
    if(!isset($FOLDER)){
        echo json_encode("No Folder");
    }else
        echo json_encode($FOLDER);
}

?>